﻿using Castle.DynamicProxy;
using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.Search.IBLL;
using CNKI.TPI.Web.Search.IDAO;
using CNKI.TPI.Web.Search.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CNKI.TPI.Web.Search.BLL
{
    public class FileService : BaseService, IFileService
    {
        private ICategoryDAO categoryDAO;
        private IUserDBDAO userDBDAO;
        private static string picType = "JPG,JPEG,BMP,GIF,PNG";
        private static string audioType = "MP3";
        private static string videoTypeAll = "MP4,M4V,MOV,FLV,WMV,MPG,AVI,RM";
        private static string videoType = "MP4,M4V,MOV,FLV";
        private static string docType = "PDF,CAJ";
        private char separator = Path.DirectorySeparatorChar;

        public FileService(ICategoryDAO categoryDAO, IUserDBDAO userDBDAO)
        {
            this.categoryDAO = this.generator.CreateInterfaceProxyWithTarget<ICategoryDAO>(categoryDAO, new IInterceptor[] { new LogInterceptor() });
            this.userDBDAO = this.generator.CreateInterfaceProxyWithTarget<IUserDBDAO>(userDBDAO, new IInterceptor[] { new LogInterceptor() });
        }

        /// <summary>
        /// 根据文件ID获取路径
        /// </summary>
        /// <param name="dbId"></param>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public string GetDigitalFile(int dbId, int fileId)
        {
            return GetFile(dbId, fileId);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbId"></param>
        /// <param name="recordId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string GetFirstDigitalFileByType(int dbId, int recordId, MediaType type)
        {
            return GetFileByType(dbId, recordId, type);
        }
        /// <summary>
        ///  /// 根据recordid找到第一个文件的路径
        /// </summary>
        /// <param name="dbId"></param>
        /// <param name="recordId"></param>
        /// <returns></returns>
        public string GetFirstDigitalFile(int dbId, int recordId)
        {
            return GetFirstFileByRecordID(dbId, recordId);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbId"></param>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public string GetSmallPic(int dbId, int fileId)
        {
            SYS_CMS_DATABASE list = categoryDAO.GetDatabaseByID(dbId);
            if (list == null)
                return "";
            METADATA_FILE_IMAGE imgFile = userDBDAO.GetSmallPic(fileId, list.DatabaseCode);
            if (imgFile == null)
                return "";
            METADATA_FILE fileInfo = userDBDAO.GetSingleFile(imgFile.FILEID, list.DatabaseCode);
            if (fileInfo == null)
            {
                return "";
            }

            return list.FilePath + separator + list.DatabaseCode + separator + "Images" + separator + GetDirByName(fileInfo.FILENAME) + separator + imgFile.IMAGEFILENAME;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbId"></param>
        /// <param name="fileId"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public string GetSmallPic(int dbId, int fileId, string filename)
        {
            SYS_CMS_DATABASE list = categoryDAO.GetDatabaseByID(dbId);
            if (list == null)
                return "";
            METADATA_FILE_IMAGE file = userDBDAO.GetSmallPic(fileId, list.DatabaseCode);
            if (file == null)
                return "";
            return list.FilePath + separator + list.DatabaseCode + separator + "Images" + separator + GetDirByName(filename) + separator + file.IMAGEFILENAME;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbId"></param>
        /// <param name="recordId"></param>
        /// <returns></returns>
        public string GetFirstSmallPic(int dbId, int recordId)
        {
            SYS_CMS_DATABASE list = categoryDAO.GetDatabaseByID(dbId);
            string result = "";
            if (list == null)
                return "";
            IList<METADATA_FILE> fileList = userDBDAO.GetFile(recordId, list.DatabaseCode);
            if (fileList == null)
            {
                return "";
            }
            foreach (METADATA_FILE file in fileList)
            {
                result = GetSmallPic(dbId, file.SYSID, file.FILENAME);
                if (!string.IsNullOrEmpty(result))
                {
                    break;
                }
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sFileName"></param>
        /// <returns></returns>
        public string GetDirByName(string sFileName)
        {
            if ((sFileName == null) || sFileName == "")
                return "";

            long lSum = 0;
            byte[] abyResult;

            abyResult = System.Text.Encoding.GetEncoding("GB2312").GetBytes(sFileName.ToLower());
            for (int i = 0; i < abyResult.Length; i++)
            {
                if (abyResult[i] >= 0x80)
                    lSum += 0xFF00L + abyResult[i]; //TPI系统的处理方法：每个字节转化为WORD再相加,所以小于0的前面要补齐1
                else
                    lSum += abyResult[i];
            }
            lSum %= 1000;
            return lSum.ToString();
        }
        /// <summary>
        /// 判断文件是否存在，是否支持播放  //0 不存在；1存在；2不支持 
        /// </summary>
        /// <param name="type"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public string ParseFile(MediaType type, string filePath)
        {
            LogOpr.Debug("FilePath="+ filePath);
            //0 不存在；1存在；2不支持 
            string result = "0";
            if (!ResourceHelper.CheckFileExist(filePath))
            {
                return result;
            }
            string fileType = filePath.Substring(filePath.LastIndexOf(".") + 1).ToUpper();

            if (type == MediaType.Audio)
            {
                if (audioType.Split(',').Contains(fileType))
                    result = "1";
                else
                    result = "2";
            }
            else if (type == MediaType.Video)
            {
                if (videoType.Split(',').Contains(fileType))
                    result = "1";
                else
                    result = "2";
            }
            else if (type == MediaType.Doc || type == MediaType.Ebook)
            {
                if (docType.Split(',').Contains(fileType))
                    result = "1";
                else
                    result = "2";
            }
            else if (type == MediaType.Pic)
            {
                if (picType.Split(',').Contains(fileType))
                    result = "1";
                else
                    result = "2";

            }
            return result;
        }

        /// <summary>
        /// 判断是否超过最大下载数
        /// </summary>
        /// <param name="dbID">数据库ID</param>
        /// <returns>0 未超过 1 超过每日下载数 2 超过总下载数</returns>
        public int GetFileDownloadLimiteInfo(int dbID)
        {
            int result = 0;
            try
            {
                if (SessionHelper.IsUserInfoExsit())
                {
                    LoginUserInfo userInfo = SessionHelper.GetUserInfo();
                    int[] downloadInfo = userDBDAO.GetUserDownloadInfo(dbID, userInfo.UserID);
                    UserDBInfo dbInfo = userInfo.DBInfo.Where(c => c.DBID == dbID).ToList()[0];
                    if (downloadInfo[0] >= dbInfo.DownloadPerDay && dbInfo.DownloadPerDay != 0)
                    {
                        result = 1;
                    }
                    else if (downloadInfo[1] >= dbInfo.TotalDownload && dbInfo.TotalDownload != 0)
                    {
                        result = 2;
                    }
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }
        /// <summary>
        /// 获取第一条符合格式的数据
        /// </summary>
        /// <param name="dbId"></param>
        /// <param name="recordId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private string GetFileByType(int dbId, int recordId, MediaType type)
        {
            SYS_CMS_DATABASE list = categoryDAO.GetDatabaseByID(dbId);
            if (list == null)
                return "";
            IList<METADATA_FILE> fileList = userDBDAO.GetFile(recordId, list.DatabaseCode);
            if (fileList == null)
            {
                return "";
            }
            foreach (METADATA_FILE file in fileList)
            {
                if (type == MediaType.Pic)
                {
                    if (picType.Split(',').Contains(file.FORMAT.ToUpper()))
                        return list.FilePath + separator + list.DatabaseCode + separator + "Pages" + separator + GetDirByName(file.FILENAME) + separator + file.FILENAME;
                }
                else if (type == MediaType.Audio)
                {
                    if (audioType.Split(',').Contains(file.FORMAT.ToUpper()))
                        return list.FilePath + separator + list.DatabaseCode + separator + "Pages" + separator + GetDirByName(file.FILENAME) + separator + file.FILENAME;
                }
                else if (type == MediaType.Doc || type == MediaType.Ebook)
                {
                    if (docType.Split(',').Contains(file.FORMAT.ToUpper()))
                        return list.FilePath + separator + list.DatabaseCode + separator + "Pages" + separator + GetDirByName(file.FILENAME) + separator + file.FILENAME;
                }
                else if (type == MediaType.Video)
                {
                    if (videoTypeAll.Split(',').Contains(file.FORMAT.ToUpper().ToUpper()))
                        return list.FilePath + separator + list.DatabaseCode + separator + "Pages" + separator + GetDirByName(file.FILENAME) + separator + file.FILENAME;
                }
            }
            return "";
        }
        private string GetFile(int dbId, int fileId)
        {
            SYS_CMS_DATABASE list = categoryDAO.GetDatabaseByID(dbId);
            if (list == null)
                return "";
            METADATA_FILE file = userDBDAO.GetSingleFile(fileId, list.DatabaseCode);
            if (file == null)
                return "";
            return list.FilePath + separator + list.DatabaseCode + separator + "Pages" + separator + GetDirByName(file.FILENAME) + separator + file.FILENAME;
        }

        public static bool CheckVideo(string type)
        {
            bool result = false;
            try
            {
                if (videoType.Contains(type.ToUpper()))
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        public static bool CheckDoc(string type)
        {
            bool result = false;
            try
            {
                if (docType.Contains(type.ToUpper()))
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        public static bool CheckAudio(string type)
        {
            bool result = false;
            try
            {
                if (audioType.Contains(type.ToUpper()))
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }
        public static bool CheckPic(string type)
        {
            bool result = false;
            try
            {
                if (picType.Contains(type.ToUpper()))
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 根据文件ID找到文件路径
        /// </summary>
        /// <param name="dbId"></param>
        /// <param name="fileid"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string FileIsExitByFileID(int dbId, int fileid)
        {
            return GetFile(dbId, fileid);
        }

        private string GetFirstFileByRecordID(int dbId, int recordId)
        {
            SYS_CMS_DATABASE list = categoryDAO.GetDatabaseByID(dbId);
            if (list == null)
                return "";
            IList<METADATA_FILE> fileList = userDBDAO.GetFile(recordId, list.DatabaseCode);
            if (fileList == null)
            {
                return "";
            }
            else
            {
                return list.FilePath + separator + list.DatabaseCode + separator + "Pages" + separator + GetDirByName(fileList[0].FILENAME) + separator + fileList[0].FILENAME;
            }
        }


        /// <summary>
        /// 获取文件
        /// </summary>
        /// <param name="recordID"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public IList<METADATA_FILE> GetFile(int recordID, string dbName)
        {
            return userDBDAO.GetFile(recordID, dbName);
        }
    }
}
